<template>
  <div class="search">
    <div class="input-wrapper">
      <input type="text" placeholder="请输入城市名或拼音" v-model="keyword" />
    </div>
    <div class="search-content" v-show="keyword">
      <ul>
        <li v-for="item in list" :key="item.id" @click="cityClick(item.name)">{{item.name}}</li>
        <li v-show="hasKeyword" class="noKeyWord">没有找到匹配项</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from "vuex";
export default {
  name: "CitySearch",
  data() {
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  methods: {
    cityClick(city) {
      // this.$store.dispatch("changeCity", city);
      // this.$store.commit("changeCity", city);
      this.changeCity(city);
      this.keyword = "";
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"])
  },
  props: {
    cities: {}
  },
  watch: {
    keyword() {
      if (this.timer) clearTimeout(this.timer);
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (const key in this.cities) {
          this.cities[key].forEach(item => {
            if (
              item.name.includes(this.keyword) ||
              item.spell.includes(this.keyword)
            ) {
              result.push(item);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  },
  computed: {
    hasKeyword() {
      return !this.list.length;
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~@/assets/style/variables'

.search
  width: 100%
  height: 0.8rem
  background: $bgColor
  .input-wrapper
    width: 100%
    padding: 0.1rem 0
    input
      width: 80%
      height: 0.6rem
      outline: none
      display: block
      margin: 0 auto
      border: 1px solid $bgColor
      border-radius: 0.08rem
      text-align: center
      color: #ccc
      font-size: 0.28rem
  .search-content
    position: absolute
    top: 1.68rem
    left: 0
    right: 0
    bottom: 0
    z-index: 100
    background: #fff
    ul
      width: 100%
      li
        height: 0.8rem
        line-height: 0.8rem
        border-bottom: 1px solid #ccc
        font-size: 0.28rem
        padding: 0 0.2rem
      .noKeyWord
        border-bottom: none
</style>
